package nosql.query;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import nosql.util.Pair;

/**
 * The result include the entityId and JSON string. In form {entityId: id, json}
 * @author Yexi Jiang <http://sites.google.com/site/yexijiang/>
 *
 */
public class QueryResult{
	private List<Pair<String, Map<String, Object>>> results;
	
	public QueryResult(List<Pair<String, Map<String, Object>>> results){
		this.results = results;
	}

	public List<String> getJSON(){
		List<String> jsonList = new ArrayList<String>();
		for(Pair<String, Map<String, Object>> result : results){
			String entityId = result.getFirst();
			Map<String, Object> properties = result.getSecond();
			StringBuilder builder = new StringBuilder();
			builder.append("{\"entityId\":\"" + entityId + "\",");
			for(Map.Entry<String, Object> entry : properties.entrySet()){
				String name = entry.getKey();
				Object value = entry.getValue();
				try{
					int iValue = Integer.parseInt(value.toString());
					builder.append("\"" + name + "\":" + iValue + ",");
				}catch(NumberFormatException e){
					try{
						double dValue = Double.parseDouble(value.toString());
						builder.append("\"" + name + "\":" + dValue + ",");
					}catch(NumberFormatException ee){
						builder.append("\"" + name + "\":" + value + ",");
					}
				}
			}
			builder.deleteCharAt(builder.length()-1);
			builder.append("}");
			jsonList.add(builder.toString());
		}
		
		return jsonList;
	}
}
